package com.skydoves.chatgpt.feature.chat.ddd.messages


import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.core_database.entities.ChatMessage
import com.skydoves.chatgpt.core.data.repository.AppUserRepository
import com.skydoves.chatgpt.core.model.network.ChatResponse
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.firstOrNull
import kotlinx.coroutines.launch
import javax.inject.Inject


@HiltViewModel
class SendToCozeViewModel@Inject constructor(
  private val userRepository: AppUserRepository,
  private val uidFlow: Flow<String>,
): ViewModel() {
  var uid = "null"

  fun getRealUid(onSuccess: (String) -> Unit){
    viewModelScope.launch {
      uid = uidFlow.firstOrNull() ?: return@launch
      onSuccess(uid)
    }
  }


  fun sendMessageToCoze(message: ChatMessage, conversationId:String, onSuccess:  (ChatResponse) -> Unit) {
    val username = message.userId
    val botId = message.botId
    val question =message.messageContent
    viewModelScope.launch {
      try {
        val response = userRepository.chat(username, botId, question,conversationId)

        if (response != null) { // 判断 response 是否不为空
          onSuccess(response)
        } else {
          println("Error: Received null response from chat API")
        }
      } catch (e: Exception) {
        println("Error: ${e.localizedMessage}")
      }
    }
  }

  fun secretChat(username:String,botId:String,conversationId: String,onSuccess: (ChatResponse) -> Unit){
    val ques="请你根据上下文和你的人设，主动和我说一句话"
    viewModelScope.launch {
      try {
        val response = userRepository.chat(username, botId, ques ,conversationId)

        if (response != null) {
          onSuccess(response)
        } else {
          println("Error: Received null response from chat API")
        }
      } catch (e: Exception) {
        println("Error: ${e.localizedMessage}")
      }
    }

  }


}